import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pt_manage/common/global.dart';
import 'package:pt_manage/component/text_icon.dart';
import 'package:pt_manage/dao/site_dao.dart';
import 'package:pt_manage/db/query/query_page.dart';
import 'package:pt_manage/generated/l10n.dart';
import 'package:pt_manage/model/Site.dart';
import 'package:pt_manage/util/toast_util.dart';

class SiteListPage extends StatefulWidget {
  const SiteListPage({super.key});

  @override
  State<SiteListPage> createState() => _SiteListPageState();
}

class _SiteListPageState extends State<SiteListPage>
    with TickerProviderStateMixin {
  final SiteDao _siteDb = Global.getDb<SiteDao>();
  final List<Site> _sites = [];
  QueryPage<Site> _page = QueryPage<Site>(page: 1, pageSize: 15);
  late SlidableController controller;
  final _animatedListGlobalKey = GlobalKey<AnimatedListState>();
  late EasyRefreshController _refreshController;

  _initWidget() {
    controller = SlidableController(this);
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
  }

  _initData() {
    _refresh();
  }

  _resetPage() {
    _page.page = 1;
    _page.pageSize = 15;
  }

  _loadSiteData() async {
    _page = await _siteDb.page(_page);
    _sites.addAll(_page.data);
    if (_page.data.isNotEmpty) {
      int start = (_page.page - 1) * _page.pageSize;
      _animatedListGlobalKey.currentState
          ?.insertAllItems(start, _sites.length - start);
    }
  }

  Future<IndicatorResult> _refresh() async {
    _resetPage();
    _sites.clear();
    _animatedListGlobalKey.currentState
        ?.removeAllItems((context, animation) => Container());
    _page.next();
    await _loadSiteData();
    _refreshController.finishRefresh();
    return IndicatorResult.success;
  }

  Future<IndicatorResult> _load() async {
    if (!_page.hasNext) return IndicatorResult.noMore;
    await _loadSiteData();
    _refreshController.finishLoad();
    return IndicatorResult.success;
  }

  @override
  void initState() {
    _initWidget();
    _initData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    const background = Colors.white;
    const onPrimary = Colors.black54;
    return EasyRefresh(
      controller: _refreshController,
      header: const CupertinoHeader(),
      footer: const CupertinoFooter(),
      onRefresh: _refresh,
      onLoad: _load,
      child: AnimatedList(
          key: _animatedListGlobalKey,
          initialItemCount: _sites.length,
          itemBuilder: (context, index, animation) {
            final site = _sites[index];
            return SizeTransition(
              sizeFactor: animation,
              axis: Axis.vertical,
              axisAlignment: 0,
              child: Container(
                  margin: const EdgeInsets.only(top: 10, left: 10, right: 10),
                  height: 70,
                  color: background,
                  child: Slidable(
                      controller: controller,
                      key: Key("key_${site.id}"),
                      useTextDirection: false,
                      enabled: true,
                      endActionPane: ActionPane(
                        extentRatio: .4,
                        motion: const ScrollMotion(),
                        // dismissible: DismissiblePane(onDismissed: () {
                        //   return;
                        // }),
                        children: [
                          const SizedBox(
                            width: 10,
                          ),
                          IconButton(
                              onPressed: () {},
                              icon: const Icon(
                                Icons.class_outlined,
                              ),
                              style: ButtonStyle(
                                  backgroundColor:
                                      WidgetStateProperty.all(background))),
                          const SizedBox(
                            width: 10,
                          ),
                          IconButton(
                              color: Colors.redAccent,
                              onPressed: () {
                                ToastUtil.showConfirmDialog(
                                    context,
                                    S.of(context).tip,
                                    S.of(context).confirmDeletionSite,
                                    onConfirm: () async {
                                  controller.close();
                                  _siteDb.removeById(site.id!);
                                  _sites.removeAt(index);
                                }, onCancel: () {});
                              },
                              icon: const Icon(
                                Icons.delete_outline,
                              ),
                              style: ButtonStyle(
                                  backgroundColor:
                                      WidgetStateProperty.all(background))),
                        ],
                      ),
                      child: Container(
                        padding: const EdgeInsets.all(10),
                        child: GestureDetector(
                          onTap: () {},
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            mainAxisSize: MainAxisSize.max,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              ConstrainedBox(
                                constraints: const BoxConstraints(
                                    minWidth: 50, maxWidth: 50),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  mainAxisSize: MainAxisSize.max,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    InkWell(
                                      onTap: () {},
                                      child: CachedNetworkImage(
                                        imageUrl: site.icon!,
                                        fit: BoxFit.fitWidth,
                                        width: 24,
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    Text(
                                      site.name!,
                                      style: const TextStyle(
                                          color: onPrimary, fontSize: 12),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                    )
                                  ],
                                ),
                              ),
                              Expanded(
                                  child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                mainAxisSize: MainAxisSize.max,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                      child: Row(
                                    mainAxisSize: MainAxisSize.max,
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      TextIcon(
                                          icon: const Icon(
                                            Icons.person,
                                            size: 16,
                                          ),
                                          text: Text(
                                            site.userInfo?.username ??
                                                'mayan50撒大大大苏打大苏打十大',
                                            style: const TextStyle(
                                                color: onPrimary, fontSize: 12),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          )),
                                      const SizedBox(
                                        width: 15,
                                      ),
                                      TextIcon(
                                          icon: const Icon(
                                            Icons.military_tech,
                                            size: 16,
                                          ),
                                          text: Text(
                                            site.userInfo?.level ??
                                                'Crazy User',
                                            style: const TextStyle(
                                                color: onPrimary, fontSize: 12),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          )),
                                      const SizedBox(
                                        width: 15,
                                      ),
                                      TextIcon(
                                          icon: const Icon(
                                            Icons.open_in_browser_outlined,
                                            size: 16,
                                          ),
                                          text: Text(
                                            site.userInfo?.inboundTime?.toString() ??
                                                '2024-06-18',
                                            style: const TextStyle(
                                                color: onPrimary, fontSize: 12),
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                          )
                                      ),
                                    ],
                                  )),
                                  Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        TextIcon(
                                          icon: Icon(Icons.download_outlined,
                                              size: 20, color: Colors.grey),
                                          text: Text("0GB"),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        TextIcon(
                                          icon: Icon(Icons.upload_outlined,
                                              size: 20, color: Colors.grey),
                                          text: Text("0GB"),
                                        ),

                                        // const Icon(Icons.download_outlined, size: 16, color: Colors.grey,),
                                      ])
                                ],
                              )),
                            ],
                          ),
                        ),
                      ))),
            );
          }),
    );
  }
}
